import logging
from logging.handlers import RotatingFileHandler
from flask import Flask, Blueprint, jsonify, request
from models import execute_query
from flask_cors import CORS, cross_origin

# 创建 Flask 应用
app = Flask(__name__)

# 配置日志记录器
handler = RotatingFileHandler('app.log', maxBytes=10000, backupCount=3, encoding='utf-8')
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
handler.setFormatter(formatter)
app.logger.addHandler(handler)
app.logger.setLevel(logging.DEBUG)

# 创建 Blueprint
course_bp = Blueprint('course_bp', __name__)
CORS(course_bp, resources={r"/*": {"methods": ["GET", "POST", "OPTIONS"], "origins": "*", "allow_headers": ["Content-Type"]}})

@course_bp.route('/api/course_categories', methods=['GET'])
@cross_origin(headers=["Content-Type"])
def get_course_categories():
    try:
        query = 'SELECT id, category_name, description FROM course.course_categories'
        result = execute_query(query, fetch=True)
        if result:
            categories = [
                {
                    'id': row[0],
                    'category_name': row[1],
                    'description': row[2]
                }
                for row in result
            ]
        else:
            categories = []
        return jsonify(categories)
    except Exception as e:
        app.logger.error(f'Error fetching course categories: {str(e)}', exc_info=True)
        return jsonify({'message': f'Error fetching course categories: {str(e)}'}), 500

@course_bp.route('/api/courses', methods=['GET'])
@cross_origin(headers=["Content-Type"])
def get_course_detail():
    try:
        category_id = request.args.get('category_id', type=int)
        user_id = request.args.get('user_id', type=int)
        if category_id is None:
            return jsonify({'message': 'category_id is required'}), 400

        query = 'SELECT id, title, description, price, category_id, created_at, updated_at FROM course.courses WHERE category_id = %s'
        result = execute_query(query, (category_id,), fetch=True)
        if result:
            courses = [
                {
                    'id': row[0],
                    'title': row[1],
                    'description': row[2],
                    'price': row[3],
                    'category_id': row[4],
                    'created_at': row[5],
                    'updated_at': row[6],
                    'is_purchased': is_course_purchased(user_id, category_id)
                }
                for row in result
            ]
            return jsonify(courses)
        else:
            return jsonify({'message': 'No courses found for the given category_id'}), 404
    except Exception as e:
        app.logger.error(f'Error fetching course details: {str(e)}', exc_info=True)
        return jsonify({'message': f'Error fetching course details: {str(e)}'}), 500
@course_bp.route('/api/course/chapter', methods=['GET'])
@cross_origin(headers=["Content-Type"])
def get_course_chapter():
    try:
        category_id = request.args.get('category_id', type=int)
        course_id = request.args.get('course_id', type=int)

        if category_id is None:
            return jsonify({'message': 'category_id is required'}), 400
        # 获取课程列表
        if course_id is not None:
            query = '''
                SELECT id, title, description, price, category_id, created_at, updated_at 
                FROM course.courses 
                WHERE category_id = %s AND id = %s
            '''
            params = (category_id, course_id)
        else:
            query = '''
                SELECT id, title, description, price, category_id, created_at, updated_at 
                FROM course.courses 
                WHERE category_id = %s
            '''
            params = (category_id,)
    
        # Execute the query
        result = execute_query(query, params, fetch=True)
        if not result:
            return jsonify({'message': 'No courses found for the given category_id'}), 404

        courses = []
        for row in result:
            course_id = row[0]
            course_info = {
                'id': row[0],
                'title': row[1],
                'description': row[2],
                'price': row[3],
                'category_id': row[4],
                'created_at': row[5],
                'updated_at': row[6],
            }
            print(course_info)
            # 获取该课程的章节信息
            queryCharpter = 'SELECT id, title, description, category_id, download_link, course_id,created_at, updated_at FROM course.courses_chapter WHERE course_id = %s'
            resultCharpter = execute_query(queryCharpter, (course_id,), fetch=True)
            if resultCharpter:
                chapters = [
                    {
                        'id': chapter_row[0],
                        'title': chapter_row[1],
                        'description': chapter_row[2],
                        'category_id': chapter_row[3],
                        'download_link': chapter_row[4],
                        'course_id': chapter_row[5],
                        'created_at': chapter_row[6],
                        'updated_at': chapter_row[7]
                    }
                    for chapter_row in resultCharpter
                ]
                course_info['chapters'] = chapters

            courses.append(course_info)

        return jsonify(courses)
    except Exception as e:
        app.logger.error(f'Error fetching course details: {str(e)}', exc_info=True)
        return jsonify({'message': f'Error fetching course details: {str(e)}'}), 500
def is_course_purchased(user_id, course_id):
    query = 'SELECT * FROM course.orders WHERE user_id = %s AND course_id = %s AND order_status=2'
    result = execute_query(query, (user_id, course_id), fetch=True)
    return len(result) > 0
# 注册 Blueprint
app.register_blueprint(course_bp)